<template>
  <div class="comment">
    <header>
      <h1>发表评论</h1>
      <hr />
    </header>
    <textarea v-model="content" placeholder="请开始BB"></textarea>

    <van-button type="danger" class="btn" @click="postcomment">提交</van-button>

    <ul class="comment-list">
      <li class="item" v-for="(comment,index) in comments" :key="comment.id">
        <header >
          <span>第{{index+1}}楼</span>
          <span>用户:{{comment.user_name}}</span>
          <span>发表时间:{{comment.add_time}}</span>
        </header>
        <div>{{comment.content}}</div>
      </li>

    </ul>
      <van-button plain type="danger" class="btn" @click="getMore">{{moreText}}</van-button>
  </div>
</template>

<script >
export default {
  data: () => ({
    content: '',
    comments: [],
    pageindex: 0,
    hasMore: false
  }),
  props: ['id'],
  created () {
    this.getcomments()
  },
  methods: {
    async getcomments () {
      if (this.hasMore !== false) return
      ++this.pageindex
      const {
        data: { status, message, count }
      } = await this.$axios.get(`api/getcomments/${this.id}?pageindex=${this.pageindex}`)
      if (status !== 0) this.$Toast(message)
      this.comments = this.comments.concat(message)
      this.hasMore = this.pageindex * 2 > count
      console.log(this.hasMore)
    },
    async postcomment () {
      const {
        data: { status, message }
      } = await this.$axios.post(`api/postcomment/${this.id}`, { content: this.content })
      if (status !== 0) this.$Toast(message)
      console.log(message)
      this.comments.unshift({
        add_time: Date.now(),
        content: this.content,
        id: Date.now(),
        user_name: '匿名用户'

      })
    },
    getMore () {
      this.getcomments()
    }
  },
  computed: {
    moreText () {
      return this.hasMore ? '被掏空了' : '加载更多'
    }
  }
}
</script>
<style lang="less" >
.comment {
  textarea {
    height: 85px;
    width: 100%;
    border: 0px;
  }
  .btn {
    width: 100%;
  }
  .comment-list{
    padding:6px 0;
    .item{
      header{
        font-size: 12px;
        display:flex;
        line-height: 30px;
        justify-content: space-between;
      }
    }
  }
}
</style>
